<?php
/**
 * Created by PhpStorm.
 * User: Aaron
 * Date: 2019/7/23
 * Time: 13:02
 */
namespace Inters\Model;

use Think\Model;

class MemberModel extends Model
{
    /**
     * 获取用户信息
     * @param $id
     * @return mixed
     */
    public function getInfo($id)
    {
        return $this->where(array('member_id' => $id))->field('username, phone, point, headpic')->find();
    }

    /**
     *  创建用户
     * @param $phone
     * @param int $password
     */
    public function createUser($phone, $password = 123456, $openid = '', $nickname = '', $headimgurl = '')
    {
        $data['phone'] = $phone;
        $data['nickname'] = empty($nickname) ? '百宝库会员' : $nickname;
        $data['password'] = strongmd5($password);
        $data['point'] = 0;
        $data['experience'] = 0;
        $data['money'] = 0;
        $data['level_id'] = 1;
        $data['is_valid_phone'] = 0;
        $data['is_valid_email'] = 0;
        $data['status'] = 1;
        $data['login_wexin'] = $openid;
        $data['create_time'] = time();
        $data['headpic'] = empty($nickname) ? C('DEFAULT_HEADPIC') : $headimgurl;
        $data['ex_invitation'] = substr(base_convert(md5(uniqid(md5(microtime(true)),true)), 16, 10), 0, 6);
        $member_id = $this->add($data);

        if ($member_id > 0) {
            //增加会员信息表记录
            $MemberInfoObj = new \Phone\Model\MemberInfoModel();
            $MemberInfoObj->member_id = $member_id;
            $MemberInfoObj->create_ip = get_client_ip();
            $MemberInfoObj->add();

            //注册赠送积分
            $MemberPointObj = new \Fwadmin\Model\MemberPointModel();
            $config = S('config');

            $MemberPointObj->add_by_register($member_id, $config['point_register']);
        }

        return $member_id;
    }



    /**
     * 写入原始token
     * @param $id
     * @param $token
     */
    public function writeToken($id, $token)
    {
        $this->where(array('member_id' => $id))->save(array('token' => $token));
    }


    /**
     * 查找原始token并销毁
     * @param $id
     */
    public  function readTokenClear($id)
    {
        $token = $this->where(array('member_id' => $id))->getField('token');

        S($token, null);
    }


    /**
     *  清除token
     * @param $id
     */
    public function clearToken($token)
    {
        $this->where(array('token' => $token))->save(array('token' => null));
    }


    /**
     * 校验手机号
     * @param $id
     * @param $phone
     * @return bool
     */
    public function verifyPhone($id, $phone)
    {
        $data = $this->where(array('member_id' => $id))->getField("phone");

        return $data == $phone;
    }
}